/*********************************************************************
 *                                                                   *
 *  Js Css Minifier ( JsCssMin )                                     *
 *  Author: Igor Kanshyn                                             *
 *  Copyright (c) 2009, Igor Kanshyn. All rights reserved.           *
 *                                                                   *
 *  JsCssMin is released under the Apache Software License.          *
 *  See LICENSE.txt for more details.                                *
 *                                                                   *
 *********************************************************************/

package org.grenader.jscssmin.model;


import org.grenader.jscssmin.JsCssProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Product: JsCssMin ( JavaScript and CSS Minifier )<br>
 * Author: Igor Kanshyn (grenader).
 * </p>
 * Date: Apr 25, 2009
 */
abstract public class ResourceGroup {
    List<Resource> resources = new ArrayList<Resource>();

    public ResourceGroup() {
    }

    public void addResource(Resource resource) {
        resources.add(resource);
    }

    public List<Resource> getResources() {
        return resources;
    }

    StringBuilder getPackageFileName() {
        StringBuilder fileNameBuilder = new StringBuilder();
        for (Resource resource : getResources()) {
            fileNameBuilder.append(removeExtension(resource.extractFileName())).append("_");
        }
        return fileNameBuilder;
    }

    /**
     * Remove fileextension if it's standart for the current resource type
     *
     * @param str
     * @return
     */
    private String removeExtension(String str) {
        if (!str.toLowerCase().endsWith(getExtension()))
            return str;
        return str.substring(0, str.length() - getExtension().length());
    }

    abstract protected String getExtension();

    abstract public String getPackageLine(String version);

    public Resource getLastResource() {
        if (resources.isEmpty())
            return null;
        else
            return resources.get(resources.size() - 1);
    }

    public void processFiles(JsCssProcessor processor) {
        processor.startGroup(this);
        for (Resource resource : getResources()) {
            processor.processGroupsResource(resource);
        }
        processor.commitGroup(this);

    }

    public String getGroupFileName(String version) {
        return getPackageFileName().toString() + "v" + version + getExtension();
    }
}